<template>
	<view class="register-container">
		<view class="logo">
			<image class="logo-img" src="/static/login.png" mode="aspectFit"></image>
			<text class="title">智能直播课堂</text>
		</view>

		<view class="form">
			<view class="input-group">
				<uni-icons type="person" size="20" color="#999" />
				<input type="text" v-model="formData.username" placeholder="请输入用户名" />
			</view>

			<view class="input-group">
				<uni-icons type="locked" size="20" color="#999" />
				<input type="password" v-model="formData.password" placeholder="请输入密码" />
			</view>

			<view class="input-group">
				<uni-icons type="locked" size="20" color="#999" />
				<input type="password" v-model="formData.confirmPassword" placeholder="请确认密码" />
			</view>

			<view class="input-group">
				<uni-icons type="phone" size="20" color="#999" />
				<input type="number" v-model="formData.phone" maxlength="11" placeholder="请输入手机号" />
			</view>

			<view class="verify-group">
				<view class="input-group verify">
					<uni-icons type="email" size="20" color="#999" />
					<input type="text" v-model="formData.code" maxlength="6" placeholder="请输入验证码" />
				</view>
				<button class="verify-btn" :disabled="counting"
					@click="getVerifyCode">{{ counting ? `${count}s后重新获取` : '获取验证码' }}</button>
			</view>

			<button class="register-btn" @click="regies">注册</button>

			<view class="login-link">
				已有账号？<text class="link" @click="goToLogin">立即登录</text>
			</view>
		</view>

		<view class="footer">
			<view class="copyright">© 2024 智能直播课堂 版权所有</view>
			<view class="policy">
				<text class="link">隐私政策</text>
				<text class="separator">|</text>
				<text class="link">用户协议</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			userType: 0, // 0表示学生，1表示教师
			formData: {
				username: '',
				password: '',
				confirmPassword: '',
				phone: '',
				code: ''
			},
			count: 60,
			counting: false,
			countTimer: null
		}
	},

	methods: {
		// 切换用户类型
		switchUserType(type) {
			this.userType = type;
		},

		// 生成6位随机验证码
		generateRandomCode() {
			return Math.floor(100000 + Math.random() * 900000).toString();
		},

		getVerifyCode() {
			if (this.counting) return;
			
			// 验证手机号
			if (!this.formData.phone) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				});
				return;
			}
			
			// 验证手机号格式
			const phoneRegex = /^1[3-9]\d{9}$/;
			if (!phoneRegex.test(this.formData.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return;
			}

			// 显示加载提示
			uni.showLoading({
				title: '发送中...'
			});

			// 模拟网络延迟
			setTimeout(() => {
				uni.hideLoading();
				
				// 生成6位随机验证码
				const verifyCode = this.generateRandomCode();
				
				// 开始倒计时
				this.counting = true;
				this.countTimer = setInterval(() => {
					this.count--;
					if (this.count <= 0) {
						clearInterval(this.countTimer);
						this.counting = false;
						this.count = 60;
						this.countTimer = null;
					}
				}, 1000);
				
				// 显示验证码（开发阶段）
				uni.showToast({
					title: `验证码: ${verifyCode}`,
					icon: 'none',
					duration: 5000
				});
				
				// 自动填入验证码（开发阶段）
				setTimeout(() => {
					this.formData.code = verifyCode;
				}, 1000);
				
				console.log(`手机号 ${this.formData.phone} 的验证码: ${verifyCode}`);
			}, 1000);
		},
		regies(){
			console.log('表单数据:', this.formData);
			const { username, password, confirmPassword, phone, code } = this.formData;
			
			if (!username || !password || !confirmPassword || !phone || !code) {
				// 具体提示哪个字段为空
				let emptyFields = [];
				if (!username) emptyFields.push('用户名');
				if (!password) emptyFields.push('密码');
				if (!confirmPassword) emptyFields.push('确认密码');
				if (!phone) emptyFields.push('手机号');
				if (!code) emptyFields.push('验证码');
				
				uni.showToast({
					title: `请填写${emptyFields.join('、')}`,
					icon: 'none'
				});
				return;
			}
			
			if (this.formData.password !== this.formData.confirmPassword) {
				uni.showToast({
					title: '两次密码不一致',
					icon: 'none'
				});
				return;
			}
			
			// 验证手机号格式
			const phoneRegex = /^1[3-9]\d{9}$/;
			if (!phoneRegex.test(phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return;
			}
			
			// 验证验证码格式
			if (!/^\d{6}$/.test(code)) {
				uni.showToast({
					title: '请输入6位数字验证码',
					icon: 'none'
				});
				return;
			}
			
			// 显示加载提示
			uni.showLoading({
				title: '注册中...'
			});
			// 准备注册数据
			const registerData = {
				password: this.formData.password,
				phone: this.formData.phone,
				nickname: this.formData.username, // 使用用户名作为昵称
				role: this.userType // 0表示学生，1表示教师
			};
			console.log(registerData);
			// 发送注册请求
			uni.request({
				url: 'http://localhost:9001/user/register',
				method: 'POST',
				data: registerData,
				success: (res) => {
					uni.hideLoading();
					if (res.data && res.data.code === 200) {
						uni.showToast({
							title: '注册成功',
							icon: 'success'
						});
						
						// 获取生成的用户名（从返回数据中获取）
						const generatedUsername = res.data.data ? res.data.data.username : null;
						
						// 跳转到登录页面，并传递生成的用户名
						setTimeout(() => {
							uni.navigateBack({
								delta: 1,
								success: () => {
									// 通过事件总线传递用户名到登录页面
									uni.$emit('registerSuccess', {
										username: generatedUsername || this.formData.username
									});
								}
							});
						}, 1500);
					} else {
						uni.showToast({
							title: res.data ? res.data.message : '注册失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
					console.error('注册请求失败:', err);
				}
			});
			
		},
		handleRegister() {
			// 调试信息
			console.log('表单数据:', this.formData);
			
			// 表单验证 - 检查每个字段
			const { username, password, confirmPassword, phone, code } = this.formData;
			
			if (!username || !password || !confirmPassword || !phone || !code) {
				// 具体提示哪个字段为空
				let emptyFields = [];
				if (!username) emptyFields.push('用户名');
				if (!password) emptyFields.push('密码');
				if (!confirmPassword) emptyFields.push('确认密码');
				if (!phone) emptyFields.push('手机号');
				if (!code) emptyFields.push('验证码');
				
				uni.showToast({
					title: `请填写${emptyFields.join('、')}`,
					icon: 'none'
				});
				return;
			}

			if (this.formData.password !== this.formData.confirmPassword) {
				uni.showToast({
					title: '两次密码不一致',
					icon: 'none'
				});
				return;
			}

			// 验证手机号格式
			const phoneRegex = /^1[3-9]\d{9}$/;
			if (!phoneRegex.test(phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return;
			}

			// 验证验证码格式
			if (!/^\d{6}$/.test(code)) {
				uni.showToast({
					title: '请输入6位数字验证码',
					icon: 'none'
				});
				return;
			}

			// 显示加载提示
			uni.showLoading({
				title: '注册中...'
			});

			// 准备注册数据
			const registerData = {
				password: this.formData.password,
				phone: this.formData.phone,
				nickname: this.formData.username, // 使用用户名作为昵称
				role: this.userType // 0表示学生，1表示教师
			};
			// 发送注册请求
			uni.request({
				url: 'http://localhost:9001/user/register',
				method: 'POST',
				data: registerData,
				success: (res) => {
					uni.hideLoading();
					
					if (res.data && res.data.code === 200) {
						uni.showToast({
							title: '注册成功',
							icon: 'success'
						});
						
						// 获取生成的用户名（从返回数据中获取）
						const generatedUsername = res.data.data ? res.data.data.username : null;
						
						// 跳转到登录页面，并传递生成的用户名
						setTimeout(() => {
							uni.navigateBack({
								delta: 1,
								success: () => {
									// 通过事件总线传递用户名到登录页面
									uni.$emit('registerSuccess', {
										username: generatedUsername || this.formData.username
									});
								}
							});
						}, 1500);
					} else {
						uni.showToast({
							title: res.data ? res.data.message : '注册失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
					console.error('注册请求失败:', err);
				}
			});
		},

		goToLogin() {
			uni.navigateBack();
		}
	},

	onUnload() {
		// 页面卸载时清除定时器
		if (this.countTimer) {
			clearInterval(this.countTimer);
			this.countTimer = null;
		}
	}
}
</script>

<style scoped>
	.register-container {
		min-height: 100vh;
		background: linear-gradient(135deg, #1976D2, #64B5F6);
		padding: 20px;
		box-sizing: border-box;
	}

	.logo {
		text-align: center;
		padding: 40px 0;
	}

	.logo-img {
		width: 80px;
		height: 80px;
		margin-bottom: 20px;
	}

	.title {
		font-size: 24px;
		font-weight: bold;
		color: #fff;
	}

	.user-type-toggle {
		display: flex;
		background-color: rgba(255, 255, 255, 0.9);
		border-radius: 25px;
		margin: 0 20px 20px;
		overflow: hidden;
	}

	.toggle-item {
		flex: 1;
		text-align: center;
		padding: 12px 0;
		font-size: 16px;
		color: #666;
		transition: all 0.3s;
	}

	.toggle-item.active {
		background-color: #1976D2;
		color: #fff;
		font-weight: bold;
	}

	.form {
		background: rgba(255, 255, 255, 0.9);
		border-radius: 15px;
		padding: 20px;
		margin: 0 10px 20px;
	}

	.input-group {
		display: flex;
		align-items: center;
		border-bottom: 1px solid #eee;
		padding: 15px 0;
	}

	.input-group:last-child {
		border-bottom: none;
	}

	.input-group input {
		flex: 1;
		border: none;
		outline: none;
		font-size: 16px;
		padding-left: 10px;
		background: transparent;
	}

	.verify-group {
		display: flex;
		align-items: center;
		border-bottom: 1px solid #eee;
		padding: 15px 0;
	}

	.verify {
		flex: 1;
		border-bottom: none;
		padding: 0;
	}

	.verify-btn {
		width: 100px;
		height: 36px;
		line-height: 36px;
		background: #1976D2;
		color: #fff;
		border: none;
		border-radius: 18px;
		font-size: 14px;
		margin-left: 10px;
	}

	.verify-btn[disabled] {
		background: #ccc;
	}

	.register-btn {
		width: 100%;
		height: 45px;
		line-height: 45px;
		background: #1976D2;
		color: #fff;
		border: none;
		border-radius: 25px;
		font-size: 16px;
		margin-top: 20px;
	}

	.login-link {
		text-align: center;
		margin-top: 20px;
		color: #666;
	}

	.link {
		color: #1976D2;
	}

	.footer {
		text-align: center;
		color: rgba(255, 255, 255, 0.8);
		font-size: 12px;
		padding: 20px 0;
	}

	.policy {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 10px;
	}

	.separator {
		margin: 0 10px;
	}
</style>